<template>
  <div class="app-container">
    <el-form :inline="true" :model="listQuery" class="demo-form-inline">
      <!-- <i class="el-icon-search btn-search" @click="handleShowSearch()"></i>
       <div  v-show="showbtns==true"  class="search-lf">
      <el-form-item label="合同编号">
        <el-input style="width:100%" v-model="listQuery.contractNo" placeholder="合同编号"></el-input>
      </el-form-item>
        <el-form-item>
        <el-button  type="primary" plain  @click="getList()">查询</el-button>

      </el-form-item>

       </div> -->
      <div class="btn-box">
        <!-- '/course_list?page=' + -->
        <router-link :to="'/course_list?page=' + page">
          <el-button
            class="el-icon-arrow-left"
            type="primary"
            plain
            style="padding-left: 10px"
          >返回</el-button></router-link>
        <el-button
          type="success"
          style="margin-left: 10px"
          @click="handleAdd()"
        >新增</el-button>
        <!-- <el-button type="primary" @click="handleExport()">导入结算清单</el-button> -->
        <router-link
          :to="'/supplier_settlement_list?id=' + poId"
          style="margin-left: 10px"
        >
          <el-button type="primary" plain>查看结算清单</el-button>
        </router-link>
        <!-- <el-button
          style="margin-left:10px"

              type='primary'
          icon="el-icon-document"

        >导出excel</el-button> -->
      </div>
    </el-form>

    <el-table
      v-loading="listLoading"
      border
      height="650px"
      :data="list"
      fit
      highlight-current-row
      style="width: 100%"
    >
      <!--   @selection-change="handleSelectionChange" -->
      <el-table-column align="center" width="60px" label="序号">
        <template slot-scope="scope">
          <span>{{ scope.$index + 1 }}</span>
        </template>
      </el-table-column>
      <!-- <el-table-column type="selection" width="55"></el-table-column> -->
      <el-table-column align="center" width="130px" label="PO单号">
        <template slot-scope="{ row }">
          <span>{{ row.po }}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="课程名称">
        <template slot-scope="{ row }">
          <span>{{ row.courseName }}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="课程编导">
        <template slot-scope="{ row }">
          <template v-if="row.rowEdit">
            <el-select
              v-model="corsesList.courseChargeName"
              filterable
              placeholder="请选择"
              @change="handleCouseChangeName($event)"
            >
              <el-option
                v-for="item in courseChargeList"
                :key="item.id"
                :label="item.name"
                :value="item.name"
              />
            </el-select>
          </template>
          <span v-else>{{ row.courseChargeName }}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="课程ID">
        <template slot-scope="{ row }">
          <span>{{ row.courseId }}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" width="100px" label="供应商类型">
        <template slot-scope="{ row }">
          <template v-if="row.rowEdit">
            <el-select
              v-model="corsesList.supplierTypeName"
              filterable
              placeholder="请选择"
              @change="handleSupplierType($event)"
            >
              <el-option
                v-for="item in SupplierType"
                :key="item.id"
                :label="item.name"
                :value="item.name"
              />
            </el-select>
          </template>
          <span v-else>{{ row.supplierTypeName }}</span>
        </template>
      </el-table-column>

      <el-table-column align="center" width="200px" label="供应商名称">
        <template slot-scope="{ row }">
          <template v-if="row.rowEdit">
            <el-select
              v-model="corsesList.supplierName"
              filterable
              placeholder="请选择"
              @change="handleSupplierTypeName($event)"
            >
              <el-option
                v-for="item in SupplierTypeNameList"
                :key="item.supplierId"
                :label="item.supplierName"
                :value="item.supplierName"
              />
            </el-select>
            <!-- <el-input v-model="corsesList.supplierTypeName"></el-input> -->
          </template>
          <span v-else>{{ row.supplierName }}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="服务类型">
        <template slot-scope="{ row }">
          <template v-if="row.rowEdit">
            <el-select
              v-model="corsesList.serviceTypeName"
              filterable
              placeholder="请选择"
              @change="handleChangePro7($event)"
            >
              <el-option
                v-for="item in serviceTypeList"
                :key="item.supplierTypeId"
                :label="item.supplierTypeName"
                :value="item.supplierTypeName"
              />
            </el-select>
          </template>
          <span v-else>{{ row.serviceTypeName }}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" width="100px" label="服务名称">
        <template slot-scope="{ row }">
          <template v-if="row.rowEdit">
            <el-input v-model="corsesList.serviceName" />
          </template>
          <span v-else>{{ row.serviceName }}</span>
        </template>
      </el-table-column>
      <el-table-column class-name="status-col" width="100px" label="更新日期">
        <template slot-scope="{ row }">
          <template v-if="row.rowEdit">
            <el-date-picker
              v-model="corsesList.updateTime"
              type="date"
              placeholder="选择日期"
              format="yyyy/MM/dd"
              value-format="yyyy/MM/dd"
            />
          </template>
          <span v-else>{{ row.updateTime }}</span>
        </template>
      </el-table-column>
      <el-table-column
        class-name="status-col"
        width="120px"
        label="预估结算日期"
      >
        <template slot-scope="{ row }">
          <template v-if="row.rowEdit">
            <el-date-picker
              v-model="corsesList.estimatedSettlementDate"
              type="date"
              placeholder="选择日期"
              format="yyyy/MM/dd"
              value-format="yyyy/MM/dd"
            />
          </template>
          <span v-else>{{ row.estimatedSettlementDate }}</span>
        </template>
      </el-table-column>
      <el-table-column class-name="status-col" label="单价">
        <template slot-scope="{ row }">
          <template v-if="row.rowEdit">
            <el-input v-model="corsesList.unitPrice" />
          </template>
          <span v-else>{{ row.unitPrice }}</span>
        </template>
      </el-table-column>
      <el-table-column class-name="status-col" label="数量">
        <template slot-scope="{ row }">
          <template v-if="row.rowEdit">
            <el-input v-model="corsesList.quantity" placeholder />
          </template>
          <span v-else>{{ row.quantity }}</span>
        </template>
      </el-table-column>

      <el-table-column class-name="status-col" label="预估成本">
        <template slot-scope="{ row }">
          <span>{{ row.estimatedGenerationCost }}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="已支付">
        <template slot-scope="{ row }">
          <span>{{ row.supplierPaidAmount }}</span>
        </template>
      </el-table-column>
      <el-table-column class-name="status-col" label="未支付">
        <template slot-scope="{ row }">
          <!-- row.supplierUnpaidAmount -->
          <!-- row.quantity*row.unitPrice -->
          <span>{{ row.supplierUnpaidAmount }}</span>
        </template>
      </el-table-column>
      <el-table-column class-name="status-col" width="160px" label="供应商评级">
        <template slot-scope="{ row }">
          <!-- <el-input v-model="corsesList.estimatedGenerationCost"></el-input> -->
          <el-rate v-model="row.finalEvaluation" disabled show-score />
        </template>
      </el-table-column>
      <el-table-column class-name="status-col" width="200px" label="说明">
        <template slot-scope="{ row }">
          <template v-if="row.rowEdit">
            <el-input v-model="corsesList.description" />
          </template>
          <span v-else>{{ row.description }}</span>
        </template>
      </el-table-column>

      <el-table-column align="center" fixed="right" label="操作" width="310">
        <template slot-scope="{ row }">
          <el-button
            v-if="row.rowEdit"
            type="success"
            size="mini"
            icon="el-icon-circle-check-outline"
            @click="confirmRole(row)"
          >保存</el-button>
          <el-button
            v-else
            type="primary"
            size="mini"
            :disabled="editDisabled == true"
            icon="el-icon-edit"
            @click="handleEdit(row)"
          >编辑</el-button>
          <el-button
            :disabled="row.state == 1"
            class="mg-l"
            type="warning"
            size="mini"
            icon="el-icon-s-tools"
            @click="handleExport(row.id)"
          >生成结算清单</el-button>
          <el-button
            class="mg-l"
            type="danger"
            size="mini"
            icon="el-icon-delete"
            @click="handleDel(row.id)"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-dialog
      :visible.sync="dialogVisible"
      width="70%"
      :title="dialogType === 'edit' ? '编辑用户' : '添加服务'"
      @close="handleClose"
    >
      <el-form
        ref="corsesList"
        label-width="180px"
        :rules="rules"
        :model="corsesList"
        label-position="right"
      >
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="课程名称">
              <el-input v-model="corsesList.courseName" readonly />
            </el-form-item>

            <el-form-item label="课程编导">
              <el-input v-model="corsesList.courseChargeName" readonly />
            </el-form-item>

            <el-form-item label="供应商类型" prop="supplierTypeName">
              <!-- <el-input v-model="corsesList.productTypeName" placeholder="请选择" /> -->
              <el-select
                v-model="corsesList.supplierTypeName"
                filterable
                placeholder="请选择供应商"
                @change="handleSupplierType($event)"
              >
                <el-option
                  v-for="item in SupplierType"
                  :key="item.id"
                  :label="item.name"
                  :value="item.name"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="供应商名称" prop="supplierName">
              <el-select
                v-model="corsesList.supplierName"
                filterable
                placeholder="请选择"
                @change="handleSupplierTypeName($event)"
              >
                <el-option
                  v-for="item in SupplierTypeNameList"
                  :key="item.supplierId"
                  :label="item.supplierName"
                  :value="item.supplierName"
                />
              </el-select>
              <!-- <el-input v-model="corsesList.contractPaymentReceived" placeholder="请输入" /> -->
            </el-form-item>
            <el-form-item label="服务类型" prop="serviceTypeName">
              <!-- <el-input v-model="corsesList.productTypeName" placeholder="请选择" /> -->
              <el-select
                v-model="corsesList.serviceTypeName"
                filterable
                placeholder="请选择服务类型"
                @change="handleChangePro7($event)"
              >
                <el-option
                  v-for="item in serviceTypeList"
                  :key="item.supplierTypeId"
                  :label="item.supplierTypeName"
                  :value="item.supplierTypeName"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="服务名称" prop="serviceName">
              <el-input v-model="corsesList.serviceName" placeholder="请输入" />
            </el-form-item>
            <el-form-item label="更新日期">
              <el-date-picker
                v-model="corsesList.updateTime"
                type="date"
                placeholder="选择日期"
                format="yyyy/MM/dd"
                value-format="yyyy/MM/dd"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="预估结算日期" prop="estimatedSettlementDate">
              <el-date-picker
                v-model="corsesList.estimatedSettlementDate"
                type="date"
                placeholder="选择日期"
                format="yyyy/MM/dd"
                value-format="yyyy/MM/dd"
              />
            </el-form-item>
            <el-form-item label="单价" prop="unitPrice">
              <el-input v-model="corsesList.unitPrice" placeholder="请输入" />
            </el-form-item>
            <el-form-item label="数量" prop="quantity">
              <el-input v-model="corsesList.quantity" placeholder="请输入" />
            </el-form-item>

            <el-form-item label="供应商评级">
              <!-- <el-input v-model="" placeholder="请输入" /> -->
              {{ corsesList.finalEvaluation }}
            </el-form-item>
            <el-form-item label="说明">
              <el-input v-model="corsesList.description" placeholder="请输入" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div style="text-align: center">
        <el-button type="primary" @click="confirmRole">确定</el-button>
        <el-button
          type="danger"
          class="cancel_border"
          plain
          @click="dialogVisible = false"
        >取消</el-button>
        <!-- <el-button type="success" :disabled='isSure' @click="handleExport">导入PO管理</el-button> -->
      </div>
    </el-dialog>

    <pagination
      v-show="total >= 20"
      :total="total"
      :page.sync="listQuery.page"
      :limit.sync="listQuery.pageSize"
      @pagination="getList"
    />
  </div>
</template>

<script>
import {
  suppliersById,
  addPoCourseSupplier,
  updatePoCourseSupplier,
  delPoCourseSupplier,
  contractPO,
  getProvinces,
  poSettlement,
  suppliersList
} from '@/api/supplier'

import {
  getSupplierContent,
  getCourseCharge,
  getSupplierType,
  getSuppliersName,
  getRate,
  getServiceById,
  getRateBySupplierId
} from '@/api/remote-search'
import { regiosList } from '@/api/user'
import Pagination from '@/components/Pagination' // Secondary package based on el-pagination

export default {
  name: 'CorsesList',
  components: { Pagination },
  filters: {
    statusColorFilter(status) {
      const statusMap = {
        1: 'success',
        2: 'danger',
        3: 'warning',
        4: 'info',
        5: ' '
      }
      return statusMap[status]
    },
    statusFilter(status) {
      const statusMap = {
        1: '进行中',
        2: '已完成',
        3: '已完成',
        0: '新合同'
      }
      return statusMap[status]
    }
  },
  props: {
    isEdit: {
      type: Boolean,
      default: false
    }
  },

  data() {
    return {
      page: 0,
      rules: {
        serviceTypeName: [
          { required: true, message: '请选择服务类型', trigger: 'change' }
        ],
        supplierTypeName: [
          { required: true, message: '请选择供应商类型', trigger: 'change' }
        ],
        estimatedSettlementDate: [
          {
            type: 'string',
            required: true,
            message: '请选择预估结算日期',
            trigger: 'change'
          }
        ],

        supplierName: [
          { required: true, message: '请输入供应商名称', trigger: 'blur' }
        ],
        serviceName: [
          { required: true, message: '请输入服务名称', trigger: 'blur' }
        ],
        unitPrice: [{ required: true, message: '请输入单价', trigger: 'blur' }],

        quantity: [{ required: true, message: '请输入数量', trigger: 'blur' }]
      },
      showbtns: false,
      list: [],
      editDisabled: false,

      downloadLoading: false,
      SupplierTypeNameList: [], // 供应商名称
      courseList: [], // 课程编导list
      courseChargeList: [], // 课程编导
      SupplierType: [], // 供应商类型
      courseTypeList: [], // 课程类别
      shootModeList: [], // 拍摄形式
      CourseSchedule: [], // 课程进度
      CourseLineState: [], // 课程上线状态
      subjectTypeList: [], // 学科门类
      onlineList: [], // 上线情况
      majorList: [], // 专业分类
      multipleSelection: '', // 多选
      isSure: true,
      rowEdit: false,
      newPoId: '', // 新增之后返回的id
      downloadLoading: false,
      supplierContentList: [], // 课程编导集合
      productLineList: [], // 课程ID集合
      contracTypeList: [], // 合同类型
      provinceList: [], // 战区省份
      allProvinceList: [], // 所有省份
      regiosList: [], // 讲师姓名
      serviceTypeList: [], // 供应商服务
      corsesList: {
        // contractDeliveryDate: "",
        isTrailer: '0'
      },
      total: 0,
      dialogVisibleMenu: false,
      listLoading: true,
      listQuery: {
        access_token: sessionStorage.getItem('token'),
        page: 1,

        name: '',

        state: '',
        pageSize: 20
      },

      poId: '', // POid
      rolesList: [],

      dialogVisible: false,
      dialogType: 'new',
      checkStrictly: false,

      ids: '',
      unitPrice: 0,
      quantity: 0,

      idsPo: ''
    }
  },
  created() {
    const id = this.$route.query.id
    const poId = this.$route.query.poId
    const po = this.$route.query.po
    const corseName = this.$route.query.name
    this.page = this.$route.query.page
    console.log(this.page)
    const courseChargeName = this.$route.query.course
    this.corsesList.poCourseId = id
    this.corsesList.poId = poId
    this.corsesList.po = po
    this.poId = id
    this.corsesList.courseName = corseName
    this.corsesList.courseChargeName = courseChargeName
    this.getList(id)
    this.getListes()
  },

  methods: {
    handleClose() {
      this.editDisabled = false
    },
    handleShowSearch() {
      this.showbtns = !this.showbtns
    },
    handleCouseChangeName(id) {
      let obj = {}
      obj = this.courseChargeList.find((item) => {
        return item.name === id
      })
      this.corsesList.courseChargeId = obj.id
    },

    handleSupplierTypeName(id) {
      let obj = {}
      obj = this.SupplierTypeNameList.find((item) => {
        return item.supplierName === id
      })
      this.corsesList.supplierId = obj.supplierId
      // getRate(this.corsesList.supplierId).then((res) => {
      //   this.corsesList.finalEvaluation = res.data.finalEvaluation
      // })
      getRateBySupplierId(this.corsesList.supplierId).then(res => {
        this.corsesList.finalEvaluation = res.data.data.finalEvaluation
      })

      getServiceById(obj.supplierId).then((res) => {
        this.serviceTypeList = res.data.data
      })
    },
    handleSupplierType(id) {
      let obj = {}
      obj = this.SupplierType.find((item) => {
        return item.name === id
      })
      this.corsesList.supplierTypeId = obj.id
      getSuppliersName(obj.id).then((res) => {
        this.SupplierTypeNameList = res.data.data
      })
    },
    handleExport(id) {
      // if (this.multipleSelection.length <= 0) {
      //   this.$message.error("请选择你要更新的数据");
      //   return false;
      // }
      const data = {
        ids: id
      }
      poSettlement(data).then((res) => {
        if (res.data.code === '200') {
          this.$message.success(res.data.message + '请到供应商结算总单查看')
          this.getList(this.poId)
        } else {
          this.$message.error(res.data.message)
        }
      })
    },
    getListes() {
      getSupplierContent().then((res) => {
        this.supplierContentList = res.data.data
      })
      getCourseCharge().then((res) => {
        this.courseChargeList = res.data.data
      })
      getSupplierType().then((res) => {
        this.SupplierType = res.data.data
      })
    },
    handleSelectionChange(val) {
      this.multipleSelection = val
      console.log(this.multipleSelection)
      const res = []
      if (this.multipleSelection.length > 0) {
        this.multipleSelection.forEach((r) => {
          res.push(r.id)
        })
        this.idsPo = res.join(',')
        console.log(this.idsPo)
      }
    },
    handleChangePro7(id) {
      let obj = {}
      obj = this.serviceTypeList.find((item) => {
        return item.supplierTypeName === id
      })
      this.corsesList.serviceTypeId = obj.id
    },

    handleChangePro8(id) {
      let obj = {}
      obj = this.CourseSchedule.find((item) => {
        console.log(item)
        return item.name === id
      })
      this.corsesList.courseScheduleId = obj.id
    },

    getList(id) {
      this.listLoading = true
      suppliersById(id)
        .then((response) => {
          this.list = response.data.data

          this.listLoading = false
        })
        .catch(() => {
          this.listLoading = false
        })
    },
    handleDel(id) {
      this.$confirm('确定删除该数据?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'error'
      })
        .then(() => {
          delPoCourseSupplier(id).then((res) => {
            if (res.data.code === '200') {
              this.$message.success(res.data.message)
              this.getList(this.poId)
            } else {
              this.$message.error(res.data.message)
            }
          })
          // this.$message({
          //   type: 'success',
          //   message: '删除成功!'
          // });
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    },

    handlenewContract() {
      this.dialogType = 'new'
      this.dialogVisible = true
      // this.corsesList='';
    },
    handleEdit(row) {
      this.editDisabled = true
      this.dialogType = 'edit'

      row.rowEdit = !row.rowEdit

      this.corsesList.id = row.id
      // this.corsesList.supplierPaidAmount=row.supplierPaidAmount;
    },

    handleAdd(row) {
      // this.role = Object.assign({}, defaultRole);

      this.dialogType = 'new'
      this.dialogVisible = true
      this.$nextTick(() => {
        this.$refs['corsesList'].clearValidate()
      })
      console.log(this.corsesList)
    },
    confirmRole(row, id) {
      const isEdit = this.dialogType === 'edit'
      if (isEdit) {
        this.corsesList.state = row.state
        updatePoCourseSupplier(this.corsesList).then((res) => {
          if (res.data.code === '200') {
            this.$message.success(res.data.message)
            row.rowEdit = false
            // this.dialogVisible = false;
            this.getList(this.poId)
            this.editDisabled = false
          } else {
            this.$message.error(res.data.message)
          }
        })
        return false
      }
      const _this = this
      this.$refs['corsesList'].validate((valid) => {
        if (valid) {
          addPoCourseSupplier(this.corsesList).then((res) => {
            if ((res.data.code === '200')) {
              this.newPoId = res.data.code
              this.$message.success(res.data.message)
              this.dialogVisible = false

              this.suppliersById = '' // 清空新增数组
              this.getList(this.poId)
            }
          })
        }
      })
    }
  }
}
</script>

<style scoped>
.el-input {
  width: 50%;
}
.edit-input {
  padding-right: 100px;
}
.cancel-btn {
  position: absolute;
  right: 15px;
  top: 10px;
}
</style>
